package com.zego.wawaji.ui.wawa.synth;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.zego.wawaji.R;
import com.noble.library.basic.log.PLogger;
import com.zego.wawaji.base.module.ModuleMgr;
import com.noble.library.observer.MsgMgr;
import com.zego.wawaji.base.observer.MsgType;
import com.noble.library.observer.PObserver;
import com.zego.wawaji.base.toast.PToast;
import com.zego.wawaji.http.request.HttpResponse;
import com.zego.wawaji.http.request.RequestComplete;
import com.zego.wawaji.http.request.UrlParam;
import com.zego.wawaji.message.bean.TipsMsg;
import com.zego.wawaji.third.image.ImageLoader;
import com.zego.wawaji.ui.UIShow;
import com.zego.wawaji.ui.base.BaseAppCompatActivity;
import com.zego.wawaji.ui.base.CustomFrameLayout;
import com.zego.wawaji.ui.bean.wawa.MyWawa;
import com.zego.wawaji.ui.bean.wawa.MyWawaList;
import com.zego.wawaji.ui.bean.wawa.Wawa;
import com.zego.wawaji.ui.dialog.PickerDialogUtil;
import com.zego.wawaji.ui.play.PlayHelper;
import com.zego.wawaji.ui.view.danmuku.DanMuView;
import com.zego.wawaji.ui.view.danmuku.custom.DanMuHelper;
import com.zego.wawaji.ui.view.danmuku.custom.DanmakuEntity;
import com.zego.wawaji.ui.view.explosion.ExplosionField;
import com.zego.wawaji.ui.wawa.synth.bean.Synth;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 娃娃合成页面
 * Created by Su on 2018/2/27.
 */
public class SynthWawaActivity extends BaseAppCompatActivity implements RequestComplete, OnWawaChooseListener, View.OnClickListener, PObserver {
    private RecyclerView recyclerView;
    private SynthWawaAdapter adapter;

    private CustomFrameLayout customLayout;

    // 底部娃娃列表相关
    private MyWawaList myWawaList;
    private List<MyWawa> regWawaList = new ArrayList<>();  // 维护用户所拥有的固定娃娃列表
    private List<MyWawa> wawaList = new ArrayList<>();    // 用户操作的娃娃列表

    // 上面合成相关
    private List<ImageView> ivList = new ArrayList<>();   // 维护合成娃娃控件
    private List<Integer> iList = new ArrayList<>();

    private ImageView iv_01, iv_02, iv_03, iv_04, iv_05, iv_06;
    private static int MAX_NUM_WAWA = 6;      // 所需最多的娃娃
    private Synth synth;

    private TextView tvProp;
    private int probNum = 0;    // 概率

    // 动画效果
    private RelativeLayout rl_rotate;
    private ExplosionField mExplosionField;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        isCanBack(false);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.synth_wawa_act);
        initView();
        initResultView();
    }

    private void initView() {
        setBackView();
        setTitle("合成娃娃");

        initSynth();
        initDanmu();
        tvProp = (TextView) findViewById(R.id.synth_prop);
        mExplosionField = ExplosionField.attach2Window(this);
        customLayout = (CustomFrameLayout) findViewById(R.id.customLayout);
        customLayout.show(R.id.no_data);
        rl_rotate = (RelativeLayout) findViewById(R.id.rl_rotate);
        findViewById(R.id.btn_explain).setOnClickListener(this);
        findViewById(R.id.btn_result).setOnClickListener(this);
        findViewById(R.id.btn_synth).setOnClickListener(this);
        findViewById(R.id.btn_buy).setOnClickListener(this);
        recyclerView = (RecyclerView) findViewById(R.id.wawa_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new SynthWawaAdapter(this);
        recyclerView.setAdapter(adapter);
        adapter.setItemClickListener(this);
        reqData();
        MsgMgr.getInstance().attach(this);
    }

    private void initSynth() {
        iv_01 = (ImageView) findViewById(R.id.iv_01);
        iv_02 = (ImageView) findViewById(R.id.iv_02);
        iv_03 = (ImageView) findViewById(R.id.iv_03);
        iv_04 = (ImageView) findViewById(R.id.iv_04);
        iv_05 = (ImageView) findViewById(R.id.iv_05);
        iv_06 = (ImageView) findViewById(R.id.iv_06);
        iv_01.setOnClickListener(this);
        iv_02.setOnClickListener(this);
        iv_03.setOnClickListener(this);
        iv_04.setOnClickListener(this);
        iv_05.setOnClickListener(this);
        iv_06.setOnClickListener(this);

        ivList.add(iv_01);
        ivList.add(iv_02);
        ivList.add(iv_03);
        ivList.add(iv_04);
        ivList.add(iv_05);
        ivList.add(iv_06);
        resetiList();
    }

    /**
     * 重置iList
     */
    private void resetiList() {
        iList.clear();
        for (int i = 0; i < MAX_NUM_WAWA; i++) {
            iList.add(i);
        }
    }

    // 刷新概率视图
    private void refreshProp() {
        //int num = probNum > 100 ? 100 : probNum < 0 ? 0 : probNum;
        int num = probNum < 0 ? 0 : probNum;
        tvProp.setText("当前合成概率: " + num + "%");
    }

    private void reqData() {
        ModuleMgr.getWawaMgr().reqSynthWawa(this);
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        if (response.getUrlParam() == UrlParam.reqMyWawa) {
            if (!response.isOk()) return;
            myWawaList = (MyWawaList) response.getBaseData();
            wawaList.clear();
            regWawaList.clear();
            wawaList = myWawaList.getSynthWawaList();
            adapter.setList(wawaList);
            regWawaList.addAll(wawaList);
            if (wawaList.size() > 0) {
                customLayout.show(R.id.wawa_list);
            }
        }

        if (response.getUrlParam() == UrlParam.reqComposeWawa) {
            if (!response.isOk()) {   // 失败
                PToast.showShort(response.getMsg());
                return;
            }
            synth = (Synth) response.getBaseData();
            resetiList();
            regWawaList.clear();
            regWawaList.addAll(wawaList);
            MsgMgr.getInstance().sendMsg(MsgType.MT_Wawa_Untreated, null);

            startAnim();
        }
    }

    @Override
    public void onChooseClick(MyWawa info, Wawa wawa, int position) {
        try {
            if (iList.size() > 0) {
                wawaList.remove(position);
                adapter.notifyItemRemoved(position);
                adapter.notifyItemRangeChanged(0, wawaList.size());
                if (wawaList.size() <= 0) {
                    customLayout.show(R.id.no_data);
                }

                int temp = iList.remove(0);
                ImageView ivTemp = ivList.get(temp);
                ivTemp.setTag(R.id.synth_wawa_key, info);
                ImageLoader.loadCircleAvatar(this, wawa.getImg(), ivTemp);

                // 更新概率
                probNum += wawa.getPr();
                refreshProp();

                MsgMgr.getInstance().delay(() -> adapter.setClickable(true), 500);
            }
        } catch (Exception e) {  // 防止快速点击数组越界异常
            PLogger.printThrowable(e);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_buy:
                if (myWawaList != null) {
                    UIShow.showSynthMaterialActivity(this);
                } else {
                    PToast.showShort("数据获取失败，请退出重新进入");
                }
                break;

            case R.id.btn_explain:
                PickerDialogUtil.showSynthExplainDialog(this);
                break;

            case R.id.btn_result:
                UIShow.showSynthGalleryActivity(this);
                break;

            case R.id.btn_synth:
                startSynth();
                break;

            case R.id.iv_01:
                refreshView(0, iv_01);
                break;

            case R.id.iv_02:
                refreshView(1, iv_02);
                break;

            case R.id.iv_03:
                refreshView(2, iv_03);
                break;

            case R.id.iv_04:
                refreshView(3, iv_04);
                break;

            case R.id.iv_05:
                refreshView(4, iv_05);
                break;

            case R.id.iv_06:
                refreshView(5, iv_06);
                break;
        }
    }

    /**
     * 合成逻辑
     */
    private void startSynth() {
        if (iList.size() >= MAX_NUM_WAWA) {
            PToast.showShort("您还未添加娃娃");
            return;
        }

        List<MyWawa> synthList = new ArrayList<>();
        synthList.addAll(regWawaList);
        synthList.removeAll(wawaList);

        int size = synthList.size();
        long[] ids = new long[size];
        for (int i = 0; i < size; i++) {
            ids[i] = synthList.get(i).getId();
        }
        ModuleMgr.getWawaMgr().reqComposeWawa(JSON.toJSONString(ids), this);
    }

    /**
     * 开始旋转等待结果动画
     */
    private void startAnim() {
        rl_rotate.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_clockwise));
        for (ImageView iv : ivList) {
            iv.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_anticlockwise));
        }
        rl_rotate.getAnimation().setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                startBomb();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

    }

    /**
     * 合成成功粒子爆炸特效
     */
    private void startBomb() {
        for (ImageView iv : ivList) {
            mExplosionField.explode(iv);
        }

        probNum = 0;
        refreshProp();

        MsgMgr.getInstance().delay(() -> {
            if (!synth.isSuccess()) {   // 合成失败
                setShowAnimation(synth_fail);
            } else {
                PlayHelper.playGameResultSound();
                setShowAnimation(synth_suc);
            }
            mExplosionField.clear();
            for (ImageView iv : ivList) {
                iv.animate().setDuration(150).setStartDelay(100).scaleX(1f).scaleY(1f).alpha(1f).start();
                ImageLoader.loadCircleAvatar(SynthWawaActivity.this, R.drawable.play_room_head, iv);
            }
        }, 1000);
    }

    private void refreshView(int position, ImageView ivHead) {
        if (iList.contains(position)) return;
        iList.add(position);
        Collections.sort(iList);
        ImageLoader.loadCircleAvatar(this, R.drawable.play_room_head, ivHead);
        Object obj = ivHead.getTag(R.id.synth_wawa_key);
        if (obj instanceof MyWawa) {
            wawaList.add(0, (MyWawa) obj);
            adapter.notifyItemInserted(0);
            adapter.notifyItemRangeChanged(0, wawaList.size());
            customLayout.show(R.id.wawa_list);

            // 更新概率
            Wawa wawa = ModuleMgr.getWawaMgr().getWawa(((MyWawa) obj).getWwTypeId());
            probNum -= wawa.getPr();
            refreshProp();
        }

    }

    // ================================== 合成结果 ====================================
    private RelativeLayout synth_suc, synth_fail;
    private ImageView synth_img;
    private TextView synth_remark;

    private void initResultView() {
        synth_suc = (RelativeLayout) findViewById(R.id.synth_suc);
        synth_fail = (RelativeLayout) findViewById(R.id.synth_fail);
        synth_img = (ImageView) findViewById(R.id.synth_img);
        synth_remark = (TextView) findViewById(R.id.synth_remark);
        synth_suc.setOnClickListener(this);   // 防点击透传
        synth_fail.setOnClickListener(this);

        findViewById(R.id.synth_close).setOnClickListener(v -> setHideAnimation(synth_suc));

        findViewById(R.id.close_fail).setOnClickListener(v -> setHideAnimation(synth_fail));
    }

    /**
     * View渐隐动画效果
     */
    public void setHideAnimation(final View view) {
        if (view == null) return;

        view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.alpha_fade_out));
        view.getAnimation().setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    /**
     * View渐现动画效果
     */
    public void setShowAnimation(final View view) {
        if (view == null) return;

        if (synth != null) {
            ImageLoader.loadCenterCrop(this, synth.getBigImg(), synth_img, 0, 0);
            synth_remark.setText("获得娃娃：" + synth.getName());
        }

        view.setVisibility(View.INVISIBLE);
        view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.alpha_fade_in));
        view.getAnimation().setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (mDanMuHelper != null) {
            mDanMuHelper.release();
            mDanMuHelper = null;
        }
        super.onDestroy();
        MsgMgr.getInstance().detach(this);
    }

    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_MyInfo_Change:
                reqData();
                probNum = 0;
                refreshProp();
                resetiList();
                for (ImageView iv : ivList) {
                    iv.animate().setDuration(150).setStartDelay(100).scaleX(1f).scaleY(1f).alpha(1f).start();
                    ImageLoader.loadCircleAvatar(SynthWawaActivity.this, R.drawable.play_room_head, iv);
                }
                break;

            case MsgType.MT_App_Notification:
                addRichDanmu((String) value);
                break;
        }
    }

    // ===================================== Danmu消息 ==============================
    private DanMuHelper mDanMuHelper;
    private DanMuView mDanMuContainerBroadcast;
    private TipsMsg tipsMsg;

    private void initDanmu() {
        mDanMuContainerBroadcast = (DanMuView) findViewById(R.id.danmaku_container_room);
        mDanMuContainerBroadcast.prepare();

        mDanMuHelper = new DanMuHelper(this);
        mDanMuHelper.add(mDanMuContainerBroadcast);
    }

    private void addRichDanmu(String content) {
        tipsMsg = new TipsMsg();
        tipsMsg.parseJson(content);

        DanmakuEntity danmakuEntity = new DanmakuEntity();
        danmakuEntity.setType(DanmakuEntity.DANMAKU_TYPE_USERCHAT);
        danmakuEntity.setName(tipsMsg.getNickName());
        danmakuEntity.setAvatar(tipsMsg.getAvatar());
        danmakuEntity.setText(tipsMsg.getContent());
        addRoomDanmaku(danmakuEntity);
    }

    /**
     * 发送一条房间内的弹幕
     */
    private void addRoomDanmaku(DanmakuEntity danmakuEntity) {
        if (mDanMuHelper != null) {
            mDanMuHelper.addDanMu(danmakuEntity, true);
        }
    }
}
